package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {
	// 数据模型驱动

	// 调用Service层
	@Autowired
	private AreaService areaService;
	// 属性驱动
	private File file;

	public void setFile(File file) {
		this.file = file;
	}

	// 文件长传
	@Action(value = "area_batchImport")
	public String update() throws Exception, IOException {

		// 获取处理上传文件对象的工具类.xls 用HSSF，相当于打开excel文件
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 打开sheet1列表
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		// 创建一个集合用来存放area
		List<Area> areas = new ArrayList<>();

		//
		for (Row row : sheet) {

			// 首行排除
			if (row.getRowNum() == 0) {

				continue;
			}

			// 跳过空行或遍历完毕结束
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			// 创建Area用来封装数据
			Area area2 = new Area();
			area2.setId(row.getCell(0).getStringCellValue());
			area2.setProvince(row.getCell(1).getStringCellValue());
			area2.setCity(row.getCell(2).getStringCellValue());
			area2.setDistrict(row.getCell(3).getStringCellValue());
			area2.setPostcode(row.getCell(4).getStringCellValue());

			// 获取省市区简码编码
			// 截取
			String province = area2.getProvince().substring(0, area2.getProvince().length() - 1);
			String city = area2.getCity().substring(0, area2.getCity().length() - 1);
			String district = area2.getDistrict().substring(0, area2.getDistrict().length() - 1);
			String[] headArray = PinYin4jUtils.getHeadByString(province + city + district);
			// 将首字母拼接
			StringBuffer buffer = new StringBuffer();
			for (String headstr : headArray) {
				buffer.append(headstr);
			}

			String shortcode = buffer.toString();
			area2.setShortcode(shortcode);
			// 获取城市简码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area2.setCitycode(citycode);
			// 将Area存放到集合中
			System.out.println(shortcode + "..." + citycode);
			areas.add(area2);
		}
		areaService.save(areas);
		return NONE;
	}

	
	//带条件的分页查询
@Action(value="area_batchPages",results={@Result(name="success",type="json")})
	public String findByParams() {
		// 封装分页查询基本参数
		Pageable pageable = new PageRequest(page - 1, rows);
		// 封装条件查询参数
		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 新建一个集合来储存条件查询结果
				List<Predicate> list = new ArrayList<>();
				// 获取第一个条件查询结果对象
				if (StringUtils.isNotBlank(model.getProvince())) {
					//查询省
					Predicate p1 = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
					list.add(p1);
				}
				if (StringUtils.isNotBlank(model.getCity())) {
					//查询市
					Predicate p2 = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(model.getCity())) {
					//查询地区
					Predicate p3 = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
					list.add(p3);
				}
				// 将所有的查询条件整合在一起，返回一个查询对象
				return cb.and(list.toArray(new Predicate[0]));

			}

		};
		// 调用sevice层
		Page<Area>  page = areaService.findByParams(specification, pageable);
		
		//将数据压入值栈顶部供拦截器转换数据至json格式；
		pushPageDataToValueStack(page);
		return SUCCESS;

	}

}
